package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.modular.dao.OrderMapper;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.dao.UserMoneyMapper;
import com.drd.dt.modular.dto.ZeroPurchaseDTO;
import com.drd.dt.modular.entity.Order;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.ITBOrdersService;
import com.drd.dt.properties.TBLMPropertyConfig;
import com.drd.dt.util.FilterGoodsUtil;
import com.drd.dt.util.ResultUtil;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkOrderDetailsGetRequest;
import com.taobao.api.response.TbkOrderDetailsGetResponse;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by 86514 on 2019/3/25.
 */
@Service
@Transactional
public class TBOrderServiceImpl implements ITBOrdersService {
    private static final Logger logger = LoggerFactory.getLogger(TBOrderServiceImpl.class);

    @Autowired
    private TBLMPropertyConfig tblmPropertyConfig;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GoldCoinServiceImpl goldCoinService;
    @Autowired
    private UserMoneyServiceImpl testMoneyService;
    @Autowired
    private UserMoneyMapper userMoneyMapper;
    @Autowired
    private FilterGoodsUtil goodsUtil;
    /**
     * 通过淘宝联盟
     * 获取订单
     */
    @Override
    public Tip getOrderByUnion(String start_time, String end_time, String order_scene, String member_type, String query_type) throws Exception {
        logger.info("核桃省钱开始从淘宝联盟获取订单......开始时间为【" + start_time + "】,结束时间为【" + end_time + "】,订单场景类型为【" + order_scene + "】,推广者角色类型为【" + member_type + "】");
        //淘宝联盟传参对象
        TbkOrderDetailsGetRequest req = new TbkOrderDetailsGetRequest();
        if (StringUtils.isEmpty(order_scene)) {
            order_scene = "1";
        }
        if (StringUtils.isEmpty(query_type)) {
            query_type = "2";//付款时间
        }
        if (!StringUtils.isEmpty(member_type)) {
            req.setMemberType(Long.valueOf(member_type));
        }
        Integer page_no = 1;
        String url = tblmPropertyConfig.getUrl();
        String appkey = tblmPropertyConfig.getAppKey();
        String secret = tblmPropertyConfig.getAppSecret();
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        req.setStartTime(start_time);
        req.setEndTime(end_time);
        req.setOrderScene(Long.valueOf(order_scene));
        req.setQueryType(Long.valueOf(query_type));
        Boolean has_next = false;
        String positionIndex = "";
        SimpleDateFormat y_m_d_h_m_s = Constant.y_M_d_H_m_s;
        String our_time = "2019-12-03 18:00:00";//这之前的订单不进库
        do {
            req.setPositionIndex(positionIndex);
            req.setPageNo(Long.valueOf(page_no));
            logger.info("【核桃省钱开始从淘宝联盟获取订单...】");
            TbkOrderDetailsGetResponse rsp = client.execute(req);
            String resultStr = rsp.getBody();
            if (!StringUtils.isEmpty(resultStr)) {
                JSONObject resultObj = JSON.parseObject(resultStr);
                JSONObject data = resultObj.getJSONObject("tbk_order_details_get_response").getJSONObject("data");
                has_next = data.getBoolean("has_next");
                positionIndex = data.getString("position_index");
                JSONArray orderLists = data.getJSONObject("results").getJSONArray("publisher_order_dto");
                if (null != orderLists) {
                    logger.info("核桃省钱从淘宝联盟获取订单为【" + orderLists.size() + "条】...");
                }
                //核桃省钱 TBLM_P_ID
                String tblmpId = tblmPropertyConfig.getpId();
                String chanaelId = tblmPropertyConfig.getChanaelId();
                if (null != orderLists && orderLists.size() > 0) {
                    List<JSONObject> orders = new ArrayList<>();
                    List<String> ids = new ArrayList<>();
                    for (Object orderList : orderLists) {
                        JSONObject detail = (JSONObject) orderList;
                        String adzone_id = detail.getString("adzone_id");
                        String child_order_id = detail.getString("trade_id");//子订单号
                        if ((order_scene.equals("1") && (tblmpId.contains(adzone_id) || chanaelId.contains(adzone_id))   || (chanaelId.contains(adzone_id) && (order_scene.equals("2") || order_scene.equals("3"))))) {//匹配订单
                            ids.add(child_order_id);
                            orders.add(detail);
                        }
                    }
                    //订单结算 订单找回
                    List<String> orderIds = ids.stream().distinct().collect(Collectors.toList());
                    //获取所有零元购商品
                    List<ZeroPurchaseDTO> lists = orderMapper.getZeroPurchases();
                    for (String order_id : orderIds) {
                        //获取相同订单的
                        List<JSONObject> orderList = orders.stream().filter(t -> t.getString("trade_id").equals(order_id)).collect(Collectors.toList());
                        String orderId = order_id;
                        if (null != orderList) {
                            logger.info("核桃省钱从淘宝联盟获取订单为【" + orderLists.size() + "条】...");
                        }
                        String refund_tag = orderList.get(0).getString("refund_tag");//是否维权标识
                        String clear_time = orderList.get(0).getString("tk_earning_time");// 结算时间
                        //  订单状态   1: 全部订单，3：订单结算，12：订单付款， 13：订单失效，14：订单成功；
                        Integer order_status = orderList.get(0).getInteger("tk_status");
                        String endtime = orderList.get(0).getString("tk_create_time");//订单时间
                        String parent_order_id = orderList.get(0).getString("trade_parent_id");//父订单号

                        if (y_m_d_h_m_s.parse(end_time).getTime() < y_m_d_h_m_s.parse(our_time).getTime()){
                            continue;
                        }

                        Integer pnumber = orderList.get(0).getInteger("item_num");//商品数量
                        String product_pic_url = orderList.get(0).getString("item_img");//商品图片
                        String special_id = orderList.get(0).getString("special_id");//会员id
                        String relation_id = orderList.get(0).getString("relation_id");//渠道关系id
                        if (!product_pic_url.startsWith("http")) {
                            product_pic_url = "http:" + product_pic_url;
                        }
                        StringBuilder goods_id = new StringBuilder();
                        StringBuilder item_title = new StringBuilder();
                        Double money = 0.0;// 非零元购效果预估
                        Double zeroMoney = 0.0;// 零元购效果预估
                        Double alipay_total_price = 0.0;//总的支付价格
                        for (int i = 0; i < orderList.size(); i++) {
                            JSONObject order = orderList.get(i);
                            String item_id = order.getString("item_id");// 商品ID
                            String title = order.getString("item_title");// 商品名称
                            //通过商品id匹配是否是零元购商品
                            List<ZeroPurchaseDTO> collect = lists.stream().filter(t -> item_id.equals(t.getGoods_id())).collect(Collectors.toList());
                            if (collect.size() > 0) {//有零元购商品
                                String anti = collect.get(0).getAnti_growth();
                                if (StringUtils.isEmpty(anti)) {
                                    anti = "0";
                                }
                                Double anti_growth = Double.valueOf(anti);//购买返价格
                                zeroMoney = zeroMoney + anti_growth;
                            } else {
                                money = money + order.getDouble("pub_share_pre_fee");// 效果预估
                            }
                            if (order_status != 13) {//订单失效（关闭）无支付总价
                                alipay_total_price = alipay_total_price + order.getDouble("alipay_total_price");//支付总价
                            }
                            if (orderList.size() > 1) {
                                goods_id.append("<" + item_id + ">");// 拼接商品ID
                                item_title.append("<" + title + ">");// 拼接商品名称
                            }else if (orderList.size() == 1) {
                                goods_id.append(item_id);// 商品ID
                                item_title.append(title);// 商品名称
                            }
                        }

                        //判断使用的有效订单号
                        Order order = orderMapper.getRepeatOrder(orderId);//先使用子订单号查询订单
                        String my_clear_time = "";//我们平台订单的结算时间
                        Integer status = 1;//我们平台订单的状态
                        String yugu_money = "";//我们平台订单的预估佣金
                        if (null != order){
                            my_clear_time = order.getClear_time();//将我们平台订单数据赋值
                            status = order.getStatus();
                            yugu_money = order.getRake_back();
                        }else {//未查询到
                            Order pidOrder = orderMapper.getRepeatOrder(parent_order_id);//使用父订单号查询
                            if (null != pidOrder){//父订单号能查询到订单时，使用父订单号
                                order = pidOrder;
                                orderId = parent_order_id;
                                my_clear_time = pidOrder.getClear_time();//将我们平台订单数据赋值
                                status = pidOrder.getStatus();
                                yugu_money = pidOrder.getRake_back();
                            }
                        }

                        if (refund_tag != null && refund_tag.equals("1")) {
                            //修改失效订单返佣
                            Map map = new HashMap();
                            map.put("status", "4");
                            map.put("order_id", orderId);
                            orderMapper.updateOrderStatus(map);//更新order表
                            if(order!=null && order.getStatus()!=4){
                                order.setStatus(4);
                                testMoneyService.updateOrderFansRake(order);
                            }
                        } else if (null != order && !StringUtils.isEmpty(orderId) && !StringUtils.isEmpty(clear_time) && StringUtils.isEmpty(my_clear_time)
                                && status != 1 && !StringUtils.isEmpty(yugu_money)) {//订单结算时 订单号和结算时间不为空
//                            goodsUtil.rakeMoneyNew(orderId, Double.valueOf(yugu_money), String.valueOf(goods_id), clear_time, zeroMoney);//返佣金
                        } else if (order_status == 13) {//  订单失效
                            if(order!=null && order.getStatus()!=4){
                                orderMapper.updateStatus(orderId);
                                order.setStatus(4);
                                testMoneyService.updateOrderFansRake(order);
                            }
                        } else if (order_status == 12 || (null == order && order_status == 3)) { // 订单付款或者 订单不存在但已结算
                            if (money > 0 || zeroMoney > 0) {
                                //1，先查询 orderId在自有order表是否存在
                                if (null != order) {
                                    //2,存在的话直接 更新
                                    Map map = new HashMap();
                                    map.put("order_id", orderId);
//                                    Double rake_back = money;
//                                    if (zeroMoney > 0) {
//                                        rake_back = money + zeroMoney;//零元购返佣
//                                    }
//                                    map.put("rake_back", rake_back);
                                    map.put("status", 2);
                                    map.put("product_id", goods_id.toString());
                                    map.put("product_name", item_title.toString());
                                    if (order.getStatus() == 3) {//本地为未支付时，需要多更新字段
                                        map.put("product_pic_url", product_pic_url);
                                        map.put("actual_amount", alipay_total_price);
                                        map.put("number", pnumber);
                                        map.put("type", "1");

                                    }
                                    logger.info("核桃省钱开始更新淘宝联盟订单付款的订单【" + orderId + "】...");
                                    if (Double.parseDouble(order.getUser_rake_back_yugu()) == 0) {
                                        orderMapper.updateOrder(map);//改走order 更新，有改动增加字段
                                        Map mapuser=new HashMap();
                                        int userid=order.getUser_id();
                                        mapuser.put("id",userid);
                                        User user=userMoneyMapper.getByUserId(mapuser);
                                        order.setStatus(2);
                                        testMoneyService.updateOrderFansRake(user,order);
                                    }
                                } else {
                                    logger.info("核桃省钱订单ID为：【" + orderId + "】的订单不存在，开始新增...");
                                    Order createOrder = new Order();
                                    Map map = new HashMap<>();
                                    User myuser;
                                    if (!TextUtils.isEmpty(relation_id)) {//没有会员 ID，分享
                                        createOrder.setBuytype(1);
                                        map.put("relation_id", relation_id);
                                        myuser = userMapper.getUserIdByRidSid(map);
                                    } else if(!TextUtils.isEmpty(special_id)){//带会员ID，自购
                                        createOrder.setBuytype(0);
                                        map.put("special_id", special_id);
                                        myuser = userMapper.getUserIdByspecial_id(map);
                                    }else {//自购
                                        createOrder.setBuytype(0);
                                        map.put("taobaoUserId", getRealTaoBaoID(orderId));
                                        myuser = userMapper.queryUseridByTaobaoid(map);
                                    }
                                    if (null != myuser) {
                                        Integer id = myuser.getId();
                                        String channel_id = myuser.getChannel_id();
                                        createOrder.setUser_id(id);
                                        createOrder.setChannel_id(channel_id);
                                        createOrder.setTaobao_rid(relation_id);
                                        createOrder.setTaobao_sid(special_id);
                                        //通过商品id匹配是否是零元购商品
                                        String goodsId = String.valueOf(goods_id);
                                        List<ZeroPurchaseDTO> collect = lists.stream().filter(t -> goodsId.contains(t.getGoods_id())).collect(Collectors.toList());
                                        if (collect.size() > 0) {//有零元购商品时
                                            createOrder.setRedpacket(0);//不使用红包
                                            createOrder.setIs_zeroParchase(true);
                                            logger.info("【用户购买零元购不使用红包...】");
                                        } else {//使用红包
                                            Integer redpacket = goldCoinService.userRedpacket(String.valueOf(String.valueOf(id)));
                                            if (null == redpacket) {
                                                redpacket = 0;
                                            }
                                            createOrder.setRedpacket(redpacket);
                                        }
                                    }

                                    if (createOrder != null && null != myuser) {
                                        createOrder.setNumber(pnumber);
                                        createOrder.setProduct_id(String.valueOf(goods_id));
                                        createOrder.setProduct_name(item_title.toString());

                                        createOrder.setActual_amount(String.valueOf(alipay_total_price));
                                        createOrder.setProduct_pic_url(product_pic_url);
                                        createOrder.setCreate_time(endtime);
                                        createOrder.setOrder_id(orderId);
                                        createOrder.setUser_rake_back("0.0");

                                        double rate=testMoneyService.getRakeBackRatebyUser(myuser);//返佣比例
                                        createOrder.setUser_rake(rate+"");
                                        if (zeroMoney > 0) {
                                            orderMapper.insertUserZeroOrder(myuser.getId(),orderId,1);// 记录一下0元购
                                            createOrder.setRake_back(String.valueOf(money+zeroMoney));//全额返
                                            createOrder.setUser_rake_back_yugu(testMoneyService.round((rate*money+zeroMoney)+""));
                                        }else{
                                            createOrder.setRake_back(String.valueOf(money+zeroMoney));
                                            createOrder.setUser_rake_back_yugu(testMoneyService.round(rate*money+""));
                                        }

                                        createOrder.setStatus(2);
                                        createOrder.setType(1);
                                        orderMapper.insert(createOrder);//新增ORDER记录
                                        if (null != myuser && createOrder != null && (money > 0 || zeroMoney > 0)){
                                            testMoneyService.updateOrderFansRake(myuser,createOrder);//新增加订单
                                        }else {
                                            logger.info("【淘宝新增订单用户为空："+orderId+"】");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }else {
                logger.info("【未获取到订单数据...】");
            }
            page_no++;
        } while (has_next);

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 获取传参的后6位交换顺序
     *
     * @param str
     */
    private String getRealTaoBaoID(String str) throws Exception {
        String s = str.substring(str.length() - 6);

        String s1 = s.substring(0, 2);
        String s2 = s.substring(2, 4);
        String s3 = s.substring(4, 6);
        return s1 + s3 + s2;
    }


}
